import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:provider/provider.dart';

import '../commont/scan_animation.dart';
import '../tool/assets.dart';
import '../tool/tool.dart';
import 'notifier.dart';

class ConnectView extends StatefulWidget {
  const ConnectView({super.key});

  @override
  State<ConnectView> createState() => _ConnectViewState();
}

class _ConnectViewState extends State<ConnectView> {
  final GlobalKey<RotateAnimationState> classBKey = GlobalKey<RotateAnimationState>();
  final TextEditingController _textFieldController = TextEditingController(text: '');
  final _bleManager = BluetoothManager.instance;
  List<BLEPeripheral> _deviceList = [];
  // int _index = -1;
  BluetoothDevice? selectDevice;

  @override
  void initState() {
    super.initState();
    listen(context);
    _textFieldController.addListener(() {
      setState(() {
        // _inputstring = _textFieldController.text;
      });
    });
  }

  @override
  void dispose() {
    _textFieldController.dispose();
    super.dispose();
  }

  ///工厂化
  Container _item(BuildContext context, String title, {bool cell = true}) {
    return Container(
      color: cell ? Colors.white : BG_GREY,
      child: ListTile(
          title: Text(title),
          tileColor: cell ? Colors.white : BG_GREY,
          textColor: cell ? Colors.black : Colors.grey,
          trailing: cell
              ? Image.asset(assets.arrow, width: 15, height: 15)
              : ScanAnimation(key: classBKey, child: Image.asset(assets.refresh, width: 20, height: 20)),
          onTap: () {
            cell ? _openCupertinoDialog(context) : _refresh(context);
          }),
    );
  }

  ///工厂化
  Container _itemSub(BuildContext context, int i) {
    final scan_d = _deviceList[i].result;
    var text;
    var key = scan_d.advertisementData.manufacturerData.keys.toList().toHexstr();
    var value = scan_d.advertisementData.manufacturerData.values.map((e) => e.toHexstr()).toList().join();

    if (scan_d.device.platformName.contains('DLG')) {
      var list = scan_d.advertisementData.msd.last;
      var msd = list.toHexstr();
      var temp1 = list.sublist(0, 2).decimal / 100;
      var temp2 = list.sublist(2, 4).decimal / 100;
      var persent = list.last.toInt();
      print('=============> $key, $value');
      print('=============> ${scan_d.advertisementData}');
      print('=============> ${msd}');
      print('=============> ${list.sublist(0, 2).toHexstr()}. |. ${list.sublist(2, 4).toHexstr()}');

      text =
          'rssi:${scan_d.rssi}  Company:<0x$key> 0x$value Details: 0x$msd \nEDR:(${scan_d.device.remoteId.str}) 温度:$temp1°C/$temp2°C 电量:$persent%';
    } else {
      text = 'rssi:${scan_d.rssi}  Company:<0x$key> 0x$value \nEDR:(${scan_d.device.remoteId.str})';
    }

    return Container(
      decoration: const BoxDecoration(
        border: Border(bottom: BorderSide(color: BG_GREY, width: 1)),
      ),
      child: ListTile(
        title: Text(scan_d.device.platformName),
        tileColor: Colors.white,
        //textColor: Colors.black,
        subtitle: Text(text),

        subtitleTextStyle: const TextStyle(fontSize: 12, color: Colors.grey),
        trailing: Image.asset(assets.select_blue, width: selectDevice == scan_d.device ? 15 : 0, height: 15),
        onTap: () {
          setState(() {
            selectDevice = scan_d.device;
            _bleManager.connect(_deviceList[i]);
          });
        },
      ),
    );
  }

  ///Android风格的弹窗
  // ignore: unused_element
  Future<void> _openMaterialDialog(BuildContext context) async {
    final String? string = await showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("输入你的名字"),
          content: TextField(
            controller: _textFieldController,
            decoration: const InputDecoration(hintText: "名字"),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context, null); // 关闭对话框
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context, _textFieldController.text); // 关闭对话框
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
    if (string == null) {
      return;
    }
    _refresh(context);
  }

  ///iOS风格的弹窗
  Future<void> _openCupertinoDialog(BuildContext context) async {
    await EasyLoading.dismiss();
    //_textFieldController.clear();
    final String? string = await showCupertinoDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: const Text(
            'Filter name',
            textAlign: TextAlign.start,
          ),
          content: CupertinoTextField(
            controller: _textFieldController,
            placeholder: '...',
          ),
          actions: [
            CupertinoDialogAction(
              child: const Text('Cancel', style: TextStyle(color: Colors.black)),
              onPressed: () {
                Navigator.pop(context, null); // 关闭对话框
              },
            ),
            CupertinoDialogAction(
              child: const Text('Confirm', style: TextStyle(color: BLUE)),
              onPressed: () {
                Navigator.pop(context, _textFieldController.text); // 关闭对话框
              },
            ),
          ],
        );
      },
    );
    if (string == null) {
      return;
    }

    _refresh(context);
  }

  ///刷新扫描
  void _refresh(BuildContext context) {
    setState(() {
      _deviceList.clear();
      classBKey.currentState?.startAnimation();
      EasyLoading.show(status: 'Scanning...', dismissOnTap: false);
      // 3秒后自动关闭
      Future.delayed(Duration(seconds: 3), () {
        EasyLoading.dismiss();
      });
    });
    _bleManager.startScan(deviceNameFilter: [_textFieldController.text]);
    _bleManager.scanResultStream.listen((p0) {
      setState(() {
        _deviceList.removeWhere(($0) => $0 == p0);
        _deviceList.add(p0);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: BG_GREY,
      body: Stack(
        children: [
          Column(
            children: [
              SizedBox(height: 20, child: Container(color: BG_GREY)),
              _item(context, 'Filter name'),
              _item(context, 'Device list', cell: false),
              Expanded(
                child: ListView.builder(
                  itemCount: _deviceList.length,
                  itemBuilder: (context, index) {
                    return _itemSub(context, index);
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

extension _ConnectViewState_ble on _ConnectViewState {
  void listen(BuildContext context) {
    String date = DateTime.now().toString();

    DeviceConnectStateNotifier bluetoothState = Provider.of<DeviceConnectStateNotifier>(context, listen: false);
    LogNotifier log = Provider.of<LogNotifier>(context, listen: false);

    _bleManager.connectionStateStream.listen((p0) {
      var per = p0.keys.first;
      var event = p0.values.first;
      bluetoothState.setConnectedDevice(per.result.device);
      switch (event) {
        case BluetoothConnectionState.connected:
          log.newLog('$date:\n${per.result.device.platformName} => 已经连接');
          print('设备已连接');
          break;
        case BluetoothConnectionState.disconnected:
          log.newLog('$date:\n${per.result.device.platformName} => 断开连接');
          print('设备已断开连接');
          // _index = -1;
          selectDevice = null;
          break;
        case BluetoothConnectionState.connecting:
          print('设备连接中');
          break;
        case BluetoothConnectionState.disconnecting:
          print('设备断开连接中');
          // _index = -1;
          selectDevice = null;
          break;
      }
    });
  }
}
